<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>英雄管理</title>
  <link rel="stylesheet" href="libs/bootstrap.min.css">
  <script src="libs/vue.js"></script>
  <script src="libs/axios.min.js"></script>
  <style>
    [v-cloak] {
      display: none;
    }

    #app tbody input {
      text-align: center;
    }

    #app .addInput {
      display: inline-block;
      width: 200px;
    }

    #app td {
      vertical-align: middle;
    }

    #app a {
      user-select: none;
    }
    #app>.container{
      position: relative;
    }
    #app>.container nav{
      top: 690px;
      position: absolute;
      width: 100%;
      text-align: center;
    }
  </style>
  <script src="libs/moment.js"></script>
  <script src="libs/layer/jquery.js"></script>
  <script src="libs/layer/layer.js"></script>
</head>
<body>
<div id="app">
  <div class="container text-center">
    <h1>王者荣耀</h1>
    <div class="clearfix">
      <input ref="addBtn" v-focus v-model="myData.name" type="text" class="addInput form-control pull-left"
             style="margin-left: 10px;"
             placeholder="请输入姓名">
      <input v-model="myData.title" type="text" class="addInput form-control pull-left" style="margin-left: 10px;"
             placeholder="请输入称号"
             @keyup.enter="addData">
      <button class="btn btn-success pull-left" style="margin-left: 10px;" @click="addData">添加</button>
      <button class="btn btn-warning pull-right" @click="getData(page.current)">刷新</button>
    </div>
    <table class="table table-bordered table-hover" style="margin-top: 20px">
      <thead>
      <tr>
        <th class="text-center">序号</th>
        <th class="text-center">英雄</th>
        <th class="text-center">称号</th>
        <th class="text-center" style="width: 30%">添加时间</th>
        <th class="text-center" style="width: 20%">操作</th>
      </tr>
      </thead>
      <tbody id="t_data">

      <tr v-for="item in list" :key="item.id" v-cloak>
        <!--        未编辑状态-->
        <template v-if="!item.isEdit">
          <td style="width: 100px" v-cloak>{{item.id}}</td>
          <td style="width: 200px" v-cloak>{{item.name}}</td>
          <td v-cloak>{{item.title}}</td>
          <td v-cloak>{{item.add_time|dateFmt}}</td>
          <td>
            <button @click="item.isEdit=!item.isEdit" type="button" class="btn btn-info">编辑</button>
            <button @click="deleteData(item.id)" type="button" class="btn btn-danger" style="margin-left: 30px">删除
            </button>
          </td>
        </template>

        <!--        编辑状态-->
        <template v-else>
          <td style="width: 100px">
            <input class="form-control" type="text" v-model="item.id" disabled>
          </td>
          <td style="width: 200px">
            <input class="form-control" type="text" v-model="item.name" @keyup.enter="updateData(item)">
          </td>
          <td>
            <input class="form-control" type="text" v-model="item.title" @keyup.enter="updateData(item)">
          </td>
          <td>
            <input class="form-control" type="text" :value="item.add_time|dateFmt" disabled>
          </td>
          <td>
            <button @click="updateData(item)" type="button" class="btn btn-success">提交</button>
            <button @click="item.isEdit=!item.isEdit" type="button" class="btn btn-default" style="margin-left: 30px">
              取消
            </button>
          </td>
        </template>
      </tr>
      </tbody>
    </table>
    <nav aria-label="Page navigation">
      <ul v-cloak class="pagination">
        <li :class="{disabled:page.current<=1}">
          <a href="javascript:" aria-label="Previous" @click="lastPage">
            <span aria-hidden="true">&laquo;</span>
          </a>
        </li>
        <li v-for="count in page.sumPage" :key="count" :class="{active:page.current===count}">
          <a href="javascript:" @click="changePage(count)">{{count}}</a>
        </li>
        <li :class="{disabled:page.current>=page.sumPage}">
          <a href="javascript:" aria-label="Next" @click="nextPage">
            <span aria-hidden="true">&raquo;</span>
          </a>
        </li>
      </ul>
    </nav>
  </div>
</div>

<script>
  //配置根路径
  axios.defaults.baseURL = 'http://localhost:3000';

  Vue.directive('focus', {
    inserted(el) {
      el.focus();
    }
  })
  new Vue({
    el: '#app',
    data: {
      page: {
        current: 1,//当前页码
        limit: 10,//每页显示的数据条数
        sumPage: 1//总页数
      },
      list: [],
      myData: {
        name: '',
        title: ''
      }
    },
    created() {
      this.getDataSize();
      this.getData(this.page.current);
    },
    methods: {
      //获取总页数
      async getDataSize() {
        const res = await axios.get(`/data`)
        this.page.sumPage = Math.ceil(res.data.length / this.page.limit);
      },
      //获取数据
      async getData(current) {
        let res = await axios.get(`/data?_page=${current}&_limit=${this.page.limit}`)
        if (res.data.length === 0) {//如果没有数据则向前一页,修复删除时的bug
          this.page.current = --current;
          res = await axios.get(`/data?_page=${this.page.current}&_limit=${this.page.limit}`)
        }
        //给每一条数据添加一个属性判断是否处于编辑状态
        res.data.forEach(item => item.isEdit = false);
        //排序
        this.list = res.data;
      },

      //改变页码
      changePage(count) {
        this.page.current = count;//改变当前全局页码
        // 重新获取数据
        this.getData(this.page.current);
      },
      //上一页
      lastPage() {
        if (this.page.current <= 1) {
          this.page.current = 1;
          return;
        }
        this.page.current--;
        this.getData(this.page.current);
      },
      //下一页
      nextPage() {
        if (this.page.current >= this.page.sumPage) {
          this.page.current = this.page.sumPage;
          return;
        }
        this.page.current++;
        this.getData(this.page.current);
      },

      //添加数据
      addData() {
        layer.confirm('是否确认添加', async () => {
          let data = {
            name: this.myData.name,
            title: this.myData.title,
            add_time: new Date().getTime()
          }
          await axios.post('/data', data);
          layer.msg('添加成功');
          //清空输入框中的内容
          this.myData.name = '';
          this.myData.title = '';

          //重新计算总页数
          await this.getDataSize();
          //重新读取数据
          this.page.current = this.page.sumPage;
          await this.getData(this.page.current);

          //重新聚焦
          this.$refs.addBtn.focus();
        })
      },
      //删除数据
      deleteData(id) {
        layer.confirm('您确认要删除吗?', async () => {
          await axios.delete('/data/' + id);
          layer.msg('删除成功');
          //重新计算总页数
          await this.getDataSize();
          //重新读取数据
          await this.getData(this.page.current);
        })
      },
      //编辑数据
      async updateData(item) {
        //修改数据
        let newData = {
          id: item.id,
          name: item.name,
          title: item.title,
          add_time: item.add_time
        }
        await axios.put('/data/' + item.id, newData);
        //更新数据
        item.isEdit = !item.isEdit;
      }
    },
    filters: {
      dateFmt(data) {
        return moment(data).format("YYYY-MM-DD HH:mm:ss");
      }
    }
  })
</script>
</body>
</html>